import 'package:flutter/material.dart';
import 'package:localstore/localstore.dart';
import 'package:quiosco_soler_2/quiosco/models/db_estante_model.dart';
import 'package:quiosco_soler_2/quiosco/widgets/file_name_down.dart';

class GridViewAfter extends StatefulWidget {
  final List<DbEstantes> elements;
  final String infoKey;
  final dynamic info;

  const GridViewAfter({
    Key? key,
    required this.elements,
    required this.infoKey,
    required this.info
  }) : super(key: key);

  @override
  State<GridViewAfter> createState() => _GridViewAfterState();
}

class _GridViewAfterState extends State<GridViewAfter> {
  final _db = Localstore.instance;

  @override
  Widget build(BuildContext context) {
    return GridView.count(
      childAspectRatio: (2/3.5),
      crossAxisCount: 3,
      children: List.generate(widget.elements.length, (index) => TextButton(
        style: TextButton.styleFrom(
          padding: EdgeInsets.zero,
          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
          minimumSize: const Size(0, 0),
        ),
        child: FileNameDown(
          name: widget.elements[index].esta!,
          image: widget.elements[index].idim!,
          date: 'Publicado el ${restartDate(widget.elements[index].fecr!)}',
        ),
        onPressed: () async{
          final id = widget.infoKey.replaceAll('/quiosco/', '');
          final info = widget.info;

          info['ides'] = widget.elements[index].ides;
          info['esta'] = widget.elements[index].esta;

          _db.collection('quiosco').doc(id).set(info);

          await Navigator.pushNamed(context, 'secc');

          final infoAct = {
            'user':        info['user'],
            'accessToken': info['accessToken'],
            'dinum':       info['dinum'],
          };

          _db.collection('quiosco').doc(id).set(infoAct);
        },
      )),
    );
  }

  String restartDate(String date){
    String year = date.substring(2, 4);
    String dbMonth = date.substring(5, 7);
    String day = date.substring(8);
    String month = "";
    switch(dbMonth){
      case '01':
        month = 'ENE';
        break;
      case '02':
        month = 'FEB';
        break;
      case '03':
        month = 'MAR';
        break;
      case '04':
        month = 'ABR';
        break;
      case '05':
        month = 'MAY';
        break;
      case '06':
        month = 'JUN';
        break;
      case '07':
        month = 'JUL';
        break;
      case '08':
        month = 'AGO';
        break;
      case '09':
        month = 'SEP';
        break;
      case '10':
        month = 'OCT';
        break;
      case '11':
        month = 'NOV';
        break;
      case '12':
        month = 'DIC';
        break;
      default:
        month = 'MES';
        break;
    }
    return '$day-$month-$year';
  }
}

