import 'dart:ui';
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';

import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/set7/chat_full_photo.dart';

import 'package:dio/dio.dart';
import 'package:open_file/open_file.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:need_resume/need_resume.dart';
import 'package:path_provider/path_provider.dart';
import 'package:octicons_icon/octicons_icon.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:cached_network_image/cached_network_image.dart';

class ReceivedMessage extends StatefulWidget {
  final String content;
  final String time;
  final String fullname;
  final String url;
  final String msgType;
  final String department;
  final String filename;

  ReceivedMessage({
    this.content,
    this.time,
    this.fullname,
    this.url,
    this.msgType,
    this.department,
    this.filename,
  });

 @override
  _ReceivedMessageState createState() => _ReceivedMessageState(
    this.content,
    this.time,
    this.fullname,
    this.url,
    this.msgType,
    this.department,
    this.filename,
  );
}

class _ReceivedMessageState extends ResumableState<ReceivedMessage> {
  final String content;
  final String time;
  final String fullname;
  final String url;
  final String msgType;
  final String department;
  final String filename;

  _ReceivedMessageState(
    this.content,
    this.time,
    this.fullname,
    this.url,
    this.msgType,
    this.department,
    this.filename,
  );
  
  @override
  void initState(){
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 0, bottom: 2),
                  child: Text(
                      department,
                    style: TextStyle(
                      fontSize: mediaQuery(context, 'w', 30),
                      color: Colors.grey[600],
                    ),
                  ),
                ),
              ],
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                    padding: const EdgeInsets.only(left: 0, bottom: 5),
                    child: Text(
                        fullname,
                      style: TextStyle(
                        fontSize: mediaQuery(context, 'w', 30),
                        color: Colors.grey[600],
                      ),
                    ),
                  ),
              ],
            ),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(15),
                              bottomLeft: Radius.circular(15),
                              bottomRight: Radius.circular(15),
                            ),
                            boxShadow: [
                              BoxShadow(
                                color: Colors.black12,
                                blurRadius: 2.0,
                                spreadRadius: 1,
                                offset: Offset(0.0, 0.0),
                              )
                            ],
                          ),
                          child : buildContentMessageReceived(
                            context, 
                            msgType, 
                            content, 
                            url,
                            filename,
                          ),
                        ),
                      ],
                    ),
                    Column(
                      mainAxisSize: MainAxisSize.max,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.all(5.0),
                          child: Text(
                            time + " น.",
                            style: TextStyle(
                              fontSize: mediaQuery(context, 'w', 30),
                              color: Colors.grey,
                            ),
                          ),
                        )
                      ],
                    ),
                  ],
                ),
              ],
            )
          ],
        ),
    );
  }

  buildContentMessageReceived(BuildContext context, msgType, String content, url, String filename) {
    var msgtype;
    if(msgType is String){
      msgtype = int.parse(msgType);
    }else{
      msgtype = msgType;
    }
    if (msgtype == 1 || msgtype == null) {
      return Container(
        constraints: BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width * .7),
          padding: EdgeInsets.only(
            top: mediaQuery(context, 'w', 20),
            bottom: mediaQuery(context, 'w', 20),
            left: mediaQuery(context, 'w', 37),
            right: mediaQuery(context, 'w', 37),
          ),
        child: Text(
          content,
          style: TextStyle(
            fontSize: mediaQuery(context, 'h', 50),
            color: Colors.black
          ),
        ),
      );
    } else if (msgtype == 2) {
      dynamic contentWidget = InkWell(
        child: Container(
          child: ClipRRect(
            child: CachedNetworkImage(
              imageUrl: url,
              useOldImageOnUrlChange: false,
              width: mediaQuery(context, 'w', 200),
              placeholder: (context, url) => SizedBox(
                child: Center(child: CircularProgressIndicator(),)),
              errorWidget: (context, url, error) =>  Icon(Icons.error),
            ),
            borderRadius: BorderRadius.circular(10),
          ),
          //constraints: BoxConstraints(maxHeight: mediaQuery(context, 'h', 900)),
        ),
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ChatFullPhoto(
                linkUrl: url, 
                fileName: filename,
                imageBase64: content, 
              ),
            ),
          );
        },
      );
      return Container(
        constraints: BoxConstraints(
          //maxHeight: mediaQuery(context, 'h', 900),
          maxWidth: MediaQuery.of(context).size.width * .45),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: contentWidget,
                )
              ],
              mainAxisAlignment: MainAxisAlignment.start,
            ),
          ],
        ),
      );
    } else if (msgtype == 3) {
      dynamic contentWidget = InkWell(
        child: Container(
          width: mediaQuery(context, 'w', 600),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(
                    OctIcons.file_symlink_file,
                  ),
                  SizedBox(width: mediaQuery(context, 'w', 20)),
                  Text(
                   content,
                    style: TextStyle(),
                  ),
                ],
              ),
              SizedBox(height: mediaQuery(context, 'h', 20)),
              Row(
                children: [
                  Flexible(
                    child: Text(
                      filename,
                      style: TextStyle(),
                    ),
                  ),
                ],
              ),
            ],
          ),
          margin: EdgeInsets.only(bottom: 10.0, right: 5),
          constraints: BoxConstraints(maxWidth: mediaQuery(context, 'w', 600)),
          //padding: EdgeInsets.fromLTRB(15.0, 10.0, 10, 10.0),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15),
          ),
        ),
        onTap: () async {
          var response;
          response = await createDownload(context, url, filename);
        },
      );
      return Container(
        padding: EdgeInsets.all(mediaQuery(context, 'w', 23)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              child: Text(
                "แนบเอกสาร",
                style: TextStyle(color: Colors.grey),
              ),
              padding: EdgeInsets.only(left: 5),
            ),
            Row(
              children: <Widget>[
                contentWidget,
              ],
              mainAxisAlignment: MainAxisAlignment.start,
            ),
          ],
        ),
      );
    }
  }

  createDownload(context, url, String filename) async {
    var status = await Permission.storage.request();
      if(status.isGranted){
        print("Build Receive download");
        Dio dio = Dio();
        var myPath = await _findLocalPath();
        print(url);
        var getRes = await dio.get(url);
        String fullpath = "";
        print(getRes.headers);
        String checkFile = getRes.headers['content-length'][0];
        String contentType = getRes.headers['content-type'][0];
        // content-disposition: attachment; filename=fileAtt.pdf
        String typefile = "." + getRes.headers['content-disposition'][0].split("filename=")[1].split(".")[1].toString();
        print("type file :: " + typefile);
        bool check = File(myPath+"/"+filename).existsSync();
        String fileName = 
          filename == "ไม่มีชื่อไฟล์" ? 
            DateTime.now().toString().substring(0,10)+"_"+Random.secure().nextInt(1000).toString()+typefile : 
            filename;
        bool select = await alertConfirm(context, "แจ้งเตือน" , "คุณต้องการดาวน์โหลด $fileName หรือไม่?  ");

        if(select){
          print("Download..  "+ url);
          print(fileName);
          if(checkFile != "0" && contentType != ""){
            String name;
            if(check){
              name = filename.toString().split(".")[0]+"("+Random.secure().nextInt(1000).toString()+")."+filename.toString().split(".")[1];
              fullpath = myPath+"/"+name;
            }else{
              name = fileName;
              fullpath = myPath+"/"+fileName;
            }
            var response = await dio.download(url, fullpath);
            if(response.statusCode == 200){
              AppLoader.showSuccess("บันทึกสำเร็จ");
              await Future.delayed(Duration(seconds: 3));
              bool result = await alertConfirm(context, "แจ้งเตือน","ต้องการเปิดไฟล์ $name หรือไม่");
              if(result){
                OpenFile.open(fullpath);
              }
            }else{
              AppLoader.showSuccess("บันทึกไม่สำเร็จ");
              
              return false;
            }
          }
        }else{
          return false;
        }
      }else{
        print("Permission Deneid");
      }
  }

  Future<String> _findLocalPath() async {
    final directory = Platform.isAndroid
        ? await ExtStorage.getExternalStoragePublicDirectory(ExtStorage.DIRECTORY_DOWNLOADS)
        : await getApplicationDocumentsDirectory();
    return directory;
  }
} // End of ReceivedMessage Class
