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

import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/set7/show_read.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: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 SendedMessage extends StatelessWidget {
  final String url;
  final String time;
  final String msgId;
  final String msgType;
  final String content;
  final String fullname;
  final String filename;
  final int readCount;

  const SendedMessage({
    this.url,
    this.time,
    this.msgId,
    this.content,
    this.msgType,
    this.fullname,
    this.readCount,
    this.filename,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(bottom: 8, top: 8),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      "PEA : " + fullname,
                      style: TextStyle(
                        fontSize: mediaQuery(context, 'w', 30),
                        color: Colors.grey[600],
                      ),
                    ),
                    SizedBox(
                      width: 15,
                    )
                  ],
                ),
              ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: <Widget>[
                Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    GestureDetector(
                      onTap: () {
                        showDialog(
                          context: context,
                          builder: (BuildContext context) =>
                              ShowRead(chatId: msgId),
                        );
                      },
                      child: readCount > 0
                          ? Text(
                              'อ่านแล้ว',
                              style: TextStyle(
                                color: Colors.grey,
                                fontSize: mediaQuery(context, 'w', 30),
                              ),
                            )
                          : Container(),
                    ),
                    Text(
                      time + ' น.',
                      style: TextStyle(
                          fontSize: mediaQuery(context, 'w', 30),
                          color: Colors.grey
                        )
                    )
                  ],
                ),
                SizedBox(width: 10),
                Container(
                  // constraints: BoxConstraints(
                  // maxWidth: MediaQuery.of(context).size.width * .45),
                  // padding: EdgeInsets.all(mediaQuery(context, 'w', 23)),
                  decoration: BoxDecoration(
                    color: Color(0xff7F3F98),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(15),
                      bottomLeft: Radius.circular(15),
                      bottomRight: Radius.circular(15),
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black26,
                        blurRadius: 2.0,
                        spreadRadius: 1,
                        offset: Offset(0.0, 0.0),
                      )
                    ],
                  ),
                  child : buildContentMessageSender(
                    context, 
                    msgType, 
                    content, 
                    url,
                    filename,
                  ),
                ),
              ],
            ),
            ],
          ),
    );
  }

  buildContentMessageSender(BuildContext context, msgType, String content, String 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.white
          ),
        ),
      );
    } else if (msgtype == 2) {
      print("buildContentMessageSender");
      dynamic contentWidget = InkWell(
        child: Container(
          child: ClipRRect(
            child: CachedNetworkImage(
              useOldImageOnUrlChange: true,
              imageUrl: url,
              width: mediaQuery(context, 'w', 200),
              placeholder: (context, url) => Center(child: CircularProgressIndicator()),
              errorWidget: (context, url, error) =>  Icon(Icons.error),
            ),
            borderRadius: BorderRadius.circular(10),
          ),
          //margin: EdgeInsets.only(bottom: 3.0, right: 3.0),
          //constraints: BoxConstraints(maxHeight: mediaQuery(context, 'h', 900)),
        ),
        
        onTap: () {
          print("Tab 1");
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ChatFullPhoto(
                linkUrl: url, 
                fileName: filename,
                imageBase64: content, 
              ),
            ),
          );
        },
      );
      return Container(
        constraints: BoxConstraints(
          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: <Widget> [
              Row(
                children: <Widget>[
                  Icon(
                    OctIcons.file_symlink_file,
                  ),
                  SizedBox(width: mediaQuery(context, 'w', 20)),
                  Text(
                   content,
                    style: TextStyle(),
                  ),
                ],
              ),
              SizedBox(height: mediaQuery(context, 'h', 20)),
              Row(
                children: <Widget>[
                  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 {
          await createDownload(context, url, filename);
          
          // var status = await Permission.storage.request();
          // print("build 1");
          // if(status.isGranted){
          //   Dio dio = Dio();
          //   var myPath = await _findLocalPath();
          //   var getRes = await dio.get(url);
          //   print(getRes.headers);

          //   String checkFile = getRes.headers['content-length'][0];
          //   String contentType = getRes.headers['content-type'][0];
          //   String fileName = getRes.headers['content-disposition'][0].split("filename=")[1];
          //   bool select = await alertConfirm(context, "แจ้งเตือน" , "คุณต้องการดาวน์โหลด $fileName หรือไม่?");

          //   if(select){
          //     print("Download..  "+ url);
          //     print(fileName);
          //     if(checkFile != "0" && contentType != ""){
          //       String fullpath = myPath+"/"+fileName;
          //       var response = await dio.download(url, fullpath);
          //       if(response.statusCode == 200){
          //         AppLoader.showSuccess("บันทึกสำเร็จ");
          //       }else{
          //         AppLoader.showSuccess("บันทึกไม่สำเร็จ");
          //       }
          //     }
          //   }
          // }else{
          //   print("Permission Deneid");
          // }
        },
      );
      return Container(
        padding: EdgeInsets.all(mediaQuery(context, 'w', 23)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              child: Text(
                "แนบเอกสาร",
                style: TextStyle(color: Colors.grey[350]),
              ),
              padding: EdgeInsets.only(left: 5),
            ),
            Row(
              children: <Widget>[
                contentWidget,
              ],
              mainAxisAlignment: MainAxisAlignment.start,
            ),
          ],
        ),
      );
    }
  }

  createDownload(context, String url, String filename) async {
    var status = await Permission.storage.request();
      print("build 1 Create Downlaoaddd");
      if(status.isGranted){
        Dio dio = Dio();
        var myPath = await _findLocalPath();
        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];
        String typefile = "."+getRes.headers['content-type'][0].split("/")[1].trim();
        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+"/"+name;
            }
            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("บันทึกไม่สำเร็จ");
            }
          }
        }
      }else{
        print("Permission Deneid");
      }
  }

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

  static urlFilter(String linkTag){
    var tag = linkTag;
    var splitStart = tag.split("href=")[1];
    return splitStart.split("target")[0].trim();
  }
}
