import 'dart:async';
import 'dart:io';
import 'package:build/build.dart';
import 'package:xml/xml.dart';

const baseType = 'zh_CN';

Builder builds(BuilderOptions options) => StringResourceBuilder();

class StringResourceBuilder implements Builder {
  @override
  Future<void> build(BuildStep buildStep) async {
    generateStringResources();
  }

  @override
  Map<String, List<String>> get buildExtensions => {
        '.xml': ['.s.dart'],
      };
}

void main() {
  generateStringResources();
}

void generateStringResources() {
  print('generateStringResources...start');
  final directory = Directory('assets/string/');

  final buffer = StringBuffer();
  final multiBuffer = StringBuffer();
  buffer.writeln('import \'package:get/get.dart\';');
  buffer.writeln();
  buffer.writeln('class StringName {');
  buffer.writeln('StringName._();');

  multiBuffer.writeln('class StringMultiSource {');
  multiBuffer.writeln('StringMultiSource._();');
  multiBuffer
      .writeln('  static const Map<String, Map<String, String>> values = {');
  directory.listSync(recursive: true).forEach((element) {
    if (element is Directory) {
      final files =
          element.listSync().where((file) => file.path.endsWith('.xml'));
      bool isBase = element.path.endsWith('base');
      String node = isBase ? baseType : element.path.split('/').last;
      for (var file in files) {
        final content = File(file.path).readAsStringSync();
        final document = XmlDocument.parse(content);
        final strings = document.findAllElements('string');
        multiBuffer.writeln('    \'$node\': {');
        for (var string in strings) {
          final name = string.getAttribute('name');
          String value = string.text;
          if (string.text.contains('\r\n')) {
            value = string.text.replaceAll('\r\n', '').trim();
          }
          if (isBase) {
            final camelCaseName = toCamelCase(name);
            buffer.writeln(
                '  static final String $camelCaseName = \'$name\'.tr;// $value');
          }
          multiBuffer.writeln('      \'$name\': \'$value\',');
        }
        multiBuffer.writeln('    },');
      }
    }
  });

  multiBuffer.writeln('  };');
  multiBuffer.writeln('}');

  buffer.writeln('}');
  buffer.writeln();
  buffer.writeln(multiBuffer.toString());

  createDirectory('lib/resource');
  final outputFile = File('lib/resource/string.gen.dart');
  outputFile.writeAsStringSync(buffer.toString());

  print('Strings file generated successfully!');
}

void createDirectory(String path) {
  final directory = Directory(path);
  if (!directory.existsSync()) {
    directory.createSync(recursive: true);
    print('Directory created: $path');
  }
}

String toCamelCase(String? snakeCase) {
  if (snakeCase == null) {
    return '';
  }
  return snakeCase.split('_').map((word) {
    if (word == snakeCase.split('_').first) {
      return word;
    } else {
      return word[0].toUpperCase() + word.substring(1);
    }
  }).join('');
}
