
// ignore_for_file: prefer_function_declarations_over_variables, avoid_init_to_null

import 'dart:convert';

import 'package:dart_framework/utils/slack/slack_data.dart';
import 'package:dart_framework/utils/system_util.dart';
import 'package:oto/oto/application.dart';
import 'package:oto/oto/commands/command.dart';
import 'package:oto/oto/data/command_data.dart';
import 'package:http/http.dart' as http;
import 'package:oto/oto/data/jira_data.dart';

class Jira extends Command {
  String? findContent(DataJiraContent? data) {
    if(data != null) {
      if(data.text != null) {
        return data.text;
      } else {
        if(data.content != null && data.content!.isNotEmpty) {
          return findContent(data.content!.first);
        } else {
          return null;
        }
      }
    } else {
      return null;
    }
  }

  @override
  Future execute(DataCommand command) async {
    var data = DataJira.fromJson(getParam(command));
    var text = '${data.id}:${data.token}';
    var base64 = base64Encode(utf8.encode(text));
    var header = 
    {
      'Content-Type': 'application/json',
      'Authorization': 'Basic $base64'
    };
    var url = 'https://${data.domain}/rest/api/3/issue/${data.issue}';
    Application.log(url);
    var response = await http.get(Uri.parse(url), headers: header);

    if(response.statusCode < 300 && response.statusCode >= 200)
    {
      Application.log(response.body);
      var issue = DataJiraIssue.fromJson(jsonDecode(response.body));
      var targetUser = issue.fields?.assignee?.emailAddress;
      if(targetUser != null)
      {
        var slackID = '';
        for(var user in data.users) {
          if(targetUser.contains(user.mail!)) {
            slackID = user.slackID!;
            break;
          }
        }

        if(slackID.isNotEmpty) {
          var arr = issue.fields?.description?.content;
          var summary = issue.fields?.summary;
          if((arr != null && arr.isNotEmpty) || summary != null) {
            String? content = "";
            if(arr != null && arr.isNotEmpty) {
              content = findContent(arr.first);
              content ??= summary!;
            } else {
              content = summary!;
            }
            var browseUrl = 'https://${data.domain}/browse/${data.issue}';
            DataSlack Function(String) getData = (channel) {
              var slackData = DataSlack(channel);

              slackData.attachments = [];
              var attachment = SlackAttachment();
              slackData.blocks = [];
              var blockSection = SlackBlockSection();
              blockSection.text = SlackBlockText();
              blockSection.text!.text = ':jira: A new Jira task has been assigned.';
              slackData.blocks!.add(blockSection);

              attachment.blocks = [];

              blockSection = SlackBlockSection();
              blockSection.text = SlackBlockText();
              blockSection.text!.type = SlackTextType.mrkdwn;
              blockSection.text!.text = '*<$browseUrl|${data.issue}> ${issue.fields?.summary}*';
              attachment.blocks!.add(blockSection);

              blockSection = SlackBlockSection();
              blockSection.text = SlackBlockText();
              blockSection.text!.text = content;
              blockSection.accessory = SlackAccessory();
              blockSection.accessory!.type = SlackActionType.button;
              blockSection.accessory!.url = browseUrl;
              blockSection.accessory!.text = SlackBlockText();
              blockSection.accessory!.text!.type = SlackTextType.plain_text;
              blockSection.accessory!.text!.text = 'Open';
              attachment.blocks!.add(blockSection);
              
              slackData.attachments!.add(attachment);
              return slackData;
            };
            await setProperty(data.setSlackData, getData(slackID));

            if(data.subChannel != null) {
              await setProperty(data.setSlackChannel, getData(data.subChannel!));
            }
          }
        } else {
          Application.log('User not found');
        }
      }
      
    }
    else
    {
      throw Exception('Request Jira API Faile: $url');
    }
    
    return simpleFuture;
  }
}
void registerJiraCommand() {
  Command.register(
    CommandType.Jira,
    () => Jira(),
    spec: const CommandSpec(
      type: CommandType.Jira,
      category: 'jira',
      dataModel: 'DataJira',
      samplePath: 'assets/yaml/sample/21_jira.yaml',
    ),
  );
}
