import 'dart:convert';
import 'dart:math';
import 'package:dio/dio.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:mwf_app/Service/loader.dart';
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';

class ChatFullPhoto extends StatelessWidget {
  final String imageBase64;
  final String linkUrl;
  final String fileName;

  const ChatFullPhoto({
    this.imageBase64,
    this.linkUrl,
    this.fileName,
  });

  Future<bool> _createFileFromString(encodedStr, url, filename) async {
    if(encodedStr != "" && url == "" ){

      Uint8List bytes = base64.decode(encodedStr);
      String dir = await _findLocalPath();
      String name = 
          filename == "ไม่มีชื่อไฟล์" ? 
            DateTime.now().day.toString()+"_"+Random.secure().nextInt(100).toString()+".png" : 
            filename;
      print(name);
      String fullPath = '$dir/$name';
      File file = File(fullPath);
      await file.writeAsBytes(bytes);
      final result = await ImageGallerySaver.saveFile(fullPath);
      return result['isSuccess'];

    }else if( encodedStr == null && url != ""){
      print(url);
      Dio dio = Dio();
      String fullpath="";
      var myPath = await _findLocalPath();
      var getRes = await dio.get(url);
      String typefile = "."+getRes.headers['content-type'][0].split("/")[1].trim();
      String fileName = 
          filename == "ไม่มีชื่อไฟล์" ? 
            DateTime.now().toString().substring(0,10)+"_"+Random.secure().nextInt(1000).toString()+typefile : 
            filename;
      bool check = File(myPath+"/"+fileName).existsSync();
      if(check){
        String name = filename.toString().split(".")[0]+"("+Random.secure().nextInt(1000).toString()+")."+filename.toString().split(".")[1];
        fullpath = myPath+"/"+name;
      }else{
        fullpath = myPath+"/"+fileName;
      }
      var response = await dio.download(url, fullpath);
      if(response.statusCode == 200){
        return true;
      }else{
        return false;
      }
    }
  }

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

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

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(
        title: const Text('รูปภาพ'),
        actions: [
          linkUrl.isEmpty ? IconButton(
            icon: Icon(
              Icons.save,
              color: Colors.white,
            ),
            onPressed: () async {
              final valid = await _createFileFromString(imageBase64, "", fileName);
              print(valid);
              if (!valid) {
                AppLoader.showError("บันทึกไม่สำเร็จ");
              }else{
                AppLoader.showSuccess("บันทึกสำเร็จ");
              }
            },
          ) : 
          IconButton(
            icon: Icon(
              Icons.save,
              color: Colors.white,
            ),
            onPressed: () async {
              final valid = await _createFileFromString(null, linkUrl, fileName);
              print(valid);
              if (!valid) {
                AppLoader.showError("บันทึกไม่สำเร็จ");
              }else{
                AppLoader.showSuccess("บันทึกสำเร็จ");
              }
              return false;
            },
          ),

        ],
      ),
      body: SingleChildScrollView(
        child: Container(
          width: double.infinity,
          constraints: BoxConstraints(minHeight: deviceSize.height - 150),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              linkUrl.isEmpty ?
              Container(
                child: Image.memory(
                  base64.decode(imageBase64),
                  width: deviceSize.width,
                  fit: BoxFit.fill,
                ),
              ) : 
              Container(
                child: Image.network(linkUrl),
                width: deviceSize.width,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
