using Godot;
using System;
using System.Collections.Generic;

namespace Rokojori
{ 
  [Tool]   
  [GlobalClass]
  public partial class SVGInkscapeLayerSeperator:Node
  {
    string _inputDirectory;

    [Export]
    public string inputDirectory
    {
      get => _inputDirectory;
      set 
      {
        _inputDirectory = value;
        
      }
    }

    [Export]
    public string outputDirectory;

    [Export]
    public bool processFlag 
    {
      get => false;
      set { if ( value ) ProcessDocuments(); }
    }

    public override void _Process( double delta )
    {

    }

    void ProcessDocuments()
    {
      var files = FilesSync.GetFiles( inputDirectory, p => p.HasFileExtension( "svg" ), true );

      for ( int i = 0; i < files.Count; i++ )
      {
        var input = files[ i ].fullPath;
        var output = outputDirectory + "/" + files[ i ].fileName + "-";
        ProcessDocument( input, output );
      }
    }

    void ProcessDocument( string inputPath, string outputPath )
    {
      var text = FilesSync.LoadUTF8( inputPath );
      var reader = new XMLReader();

      var doc = reader.Read( text );

      var layers = Inkscape.GetLayers( doc, true );
      var layerNames = Lists.Map( layers, l => Inkscape.GetLayerName( l ) );

      Inkscape.StripEditorData( doc );

      var svgElement = doc.querySelector( SVGElementName.svg );

      layers.ForEach( l => svgElement.RemoveChild( l ) );


      for ( int i = 0; i < layers.Count; i++ )
      {
        if ( layerNames[ i ].StartsWith( "__" ) )
        {
          continue;
        }

        svgElement.AppendChild( layers[ i ] );

        

        var style = SVGAttributeName.style.Get( layers[ i ] );
        var hidden = "display:none";

        if ( style == hidden )
        {
          SVGAttributeName.style.RemoveFrom( layers[ i ] );
          
        }

        var serializer = new XMLSerializer();
        var layerDocString = serializer.SerializeXMLNode( doc );

        svgElement.RemoveChild( layers[ i ] );

        FilesSync.SaveUTF8( outputPath + layerNames[ i ] + ".svg", layerDocString );

        // var layerDoc = XMLDocument.From( docString );

        // var name   = Inkscape.GetLayerName( layers[ i ] );
        // var parent = layers[ i ].parentElement;
        
        // var parentName = parent == null ? "<null>" : parent.nodeName;
        // this.LogInfo( i, name, parentName );
      }

      

      // FilesSync.SaveUTF8( inputPath + "-copy.xml", docString );
    }
  }

}