// ignore_for_file: unused_local_variable

import 'dart:async';

import 'package:color/color.dart';
import 'package:dart_framework/utils/system_util.dart';
import 'package:http/http.dart' as http;

import 'slack_data.dart';
import 'package:dart_framework/utils/string_util.dart';

enum SlackBuildType { android, ios, windows, mac, web }

class SlackSender {
  //Bot TOKEN
  String token;
  //API - https://api.slack.com/methods/chat.postMessage
  final urlMessagePost = "https://slack.com/api/chat.postMessage";
  //API - https://api.slack.com/methods/files.upload
  final urlFileUplaod = "https://slack.com/api/files.upload";

  SlackSender(this.token);

  String getValidatedUser(String? targetUser) {
    targetUser ??= "@here";
    if (targetUser.indexOf("@") != 0) targetUser = "@$targetUser";
    return targetUser;
  }

  Future sendData(DataSlack message,
      {Function(String)? completeListener,
      Function(Object)? errorListener}) async {
    return await send(message.json, completeListener: completeListener, errorListener: errorListener);
  }

  Future send(String jsonString,
      {Function(String)? completeListener,
      Function(Object)? errorListener}) async {
    String url = urlMessagePost;

    var header = 
    {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer $token'
    };
    print(jsonString);
    var response = await http.post(Uri.parse(url), headers: header, body: jsonString);

    print(response.statusCode);

    if (response.statusCode < 300 && response.statusCode >= 200) {
      print(response.body);
      if (completeListener != null)
      {
        completeListener(response.body);
        print(response.body);
      }
    } else {
      if (errorListener != null)
      {
        errorListener(response);
        print(response.body);
      }
    }

    return simpleFuture;
  }

  /// ****************** File Send *******************
  http.MultipartRequest getPostForm(
      String url, String channel) {
    var form = http.MultipartRequest('POST', Uri.parse(url));
    form.fields['token'] = token;
    form.fields['channels'] = channel;
    return form;
  }

  Future sendFile(String channel, SlackFile file,
      {Function(String)? completeListener,
      Function(Object)? errorListener}) async {
    var form = getPostForm(urlFileUplaod, channel);
    form = await file.setFileData(form);
    var response = await form.send();
    var result = await response.stream.bytesToString();
    print(result);
    if (response.statusCode < 300 && response.statusCode >= 200) {
      if (completeListener != null) completeListener(result);
    } else {
      if (errorListener != null) errorListener(result);
    }

    return simpleFuture;
  }

  /// ****************** Build Send *******************
  Future sendBuild(String appName, SlackBuildType buildType, Color color,
      String version, String downloadURL,
      {String channel = 'build'}) async {
    final buildURL = 'https://toki-labs.com/cdn/build/';
    String thumUrl = buildType == SlackBuildType.android
        ? '${buildURL}android.png'
        : '${buildURL}appstore.png';
    String projectIcon = "$buildURL$appName/icon.png";
    String emoji =
        buildType == SlackBuildType.android ? ":android1: " : ":ios0: ";
    String osColor = buildType == SlackBuildType.ios ? "#ED145B" : "#81CA3F";
    var message = DataSlack(channel);
    message.attachments = [];
    var attachments = message.attachments;

    var attachment = SlackAttachment();
    attachment.color = color.toHexColor().toCssString();
    attachment.fields = [SlackField.withParam(toPascal(appName), null)];
    attachments?.add(attachment);

    var buildTypeStr = buildTypeToString(buildType);
    attachment = SlackAttachment();
    attachment.color = osColor;
    attachment.author_name = /*emoji +*/ buildTypeStr;
    attachment.author_icon = thumUrl;
    attachment.thumb_url = projectIcon;
    attachment.fields = [
      SlackField.withParam(null,
          "Successfully build $buildTypeStr binary file.\nBuild version: *$version*")
    ];
    attachment.actions = [
      SlackAction.withParam(
          'build', 'Download', downloadURL, null, SlackActionType.button, null)
    ];
    attachments?.add(attachment);

    return await sendData(message);
  }

  String buildTypeToString(SlackBuildType type) {
    var typeStr = type.name;
    return typeStr == 'ios' ? 'iOS' : toPascal(typeStr);
  }
}
