package com.alterdekim.hearthhack.parser;


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


public class CardsXmlParser {

    private static final byte[] cardDef = "<CardDefs>".getBytes();

    private static final byte[] cardDefEnd = "</CardDefs>".getBytes();

    public static Map<String, String> parse(String path) throws IOException {
        Map<String, String> m = new HashMap<>();
        byte[] b = Files.readAllBytes(Path.of(path));
        byte[] a;
        for( int i = 0; i < b.length; i++ ) {
            if( isEq(b, i, cardDef) ) { // -8
                a = Arrays.copyOfRange(b, i-8, i-4);
                int f = findFirst(b, i);
                m.put(new String(a), new String(Arrays.copyOfRange(b, i, f)));
                i = f;
            }
        }
        return m;
    }

    private static int findFirst(byte[] b, int s) {
        for( int i = s; i < b.length; i++ ) {
            if( !isEq(b, i, cardDefEnd) ) continue;
            return i+cardDefEnd.length;
        }
        return 0;
    }

    private static boolean isEq(byte[] src, int start, byte[] m) {
        for( int i = 0; i < m.length; i++ ) {
            if( m[i] != src[start + i] ) return false;
        }
        return true;
    }
}
