// Copyright (C) 2023 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

import 'package:brick_generator/core/reader.dart';
import 'package:brick_generator/models/brick_variable.dart';
import 'package:brick_generator/models/brickgen_config.dart';
import 'package:yaml/yaml.dart';

const _nameKey = 'name';
const _descriptionKey = 'description';
const _versionKey = 'version';
const _varsKey = 'vars';
const _brickgenKey = 'brickgen';

class BrickConfig {
  BrickConfig({
    required this.name,
    required this.description,
    required this.version,
    required this.variables,
    required this.brickgenConfig,
  });

  factory BrickConfig.parse(YamlMap? data) {
    if (data == null) {
      throw ArgumentError.notNull('data');
    }

    final variables = (data[_varsKey] as YamlMap?)
        ?.entries
        .map(
          (e) => BrickVariable.fromYaml(e.key as String, e.value as YamlMap?),
        )
        .toList();

    final config = BrickConfig(
      name: data[_nameKey] as String? ?? '',
      description: data[_descriptionKey] as String? ?? '',
      version: data[_versionKey] as String? ?? '',
      variables: variables ?? [],
      brickgenConfig: BrickgenConfig.parse(data[_brickgenKey] as YamlMap?),
    );

    return config;
  }

  factory BrickConfig.fromFile(String? path) {
    if (path == null) {
      throw ArgumentError.notNull('path');
    }

    final config = YamlReader.read(path);

    return BrickConfig.parse(config);
  }

  String name;
  String description;
  String version;
  List<BrickVariable<dynamic>> variables;
  BrickgenConfig brickgenConfig;

  String toMason() {
    final content = StringBuffer('''
name: $name
description: $description

version: $version

''');

    if (variables.isNotEmpty) {
      content.writeln('vars:');
      for (final variable in variables) {
        content.writeln(variable.toMason());
      }
    }

    return content.toString();
  }

  @override
  String toString() => 'BrickConfig(name: $name, '
      'description: $description, version: $version, variables: $variables, '
      'brickgenConfig: $brickgenConfig)';
}
