package com.javarush.task.task30.task3001;

import java.math.BigInteger;

/*
Конвертер систем счислений
*/

public class Solution {
    public static void main(String[] args) {
        Number number = new Number(NumberSystemType._10, "6");
        Number result = convertNumberToOtherNumberSystem(number, NumberSystemType._2);
        System.out.println(result);    //expected 110

        number = new Number(NumberSystemType._16, "6df");
        result = convertNumberToOtherNumberSystem(number, NumberSystemType._8);
        System.out.println(result);    //expected 3337

        number = new Number(NumberSystemType._16, "abcdefabcdef");
        result = convertNumberToOtherNumberSystem(number, NumberSystemType._16);
        System.out.println(result);    //expected abcdefabcdef

        number = new Number(NumberSystemType._10, "1b");
        result = convertNumberToOtherNumberSystem(number, NumberSystemType._8);
        System.out.println(result);    //expected abcdefabcdef

    }

    private static final String nums = "0123456789abcdef";

    public static Number convertNumberToOtherNumberSystem(Number number, NumberSystem expectedNumberSystem) {
        //напишите тут ваш код
        check(number);
        long d = toDecimal(number.getDigit(), number.getNumberSystem().getNumberSystemIntValue());
        StringBuilder b = new StringBuilder();
        while (d > 0) {
            int c = (int)(d % expectedNumberSystem.getNumberSystemIntValue());
            b.append(nums.charAt(c));
            d /= expectedNumberSystem.getNumberSystemIntValue();
        }
        return new Number(expectedNumberSystem, b.reverse().toString());
    }

    private static long toDecimal(String n, int sys) {
        long res = 0;
        for (int i = 0; i < n.length(); i++) {
            int a = nums.indexOf(n.charAt(i));
            long pow = (long)Math.pow(sys, n.length() - 1 - i);
            res += a * pow;
        }
        return res;
    }

    private static void check(Number number) {
        for (int i = 0; i < number.getDigit().length(); i++) {
            int n = nums.indexOf(number.getDigit().charAt(i));
            if (n < 0 || n > number.getNumberSystem().getNumberSystemIntValue())
                throw new NumberFormatException();
        }
    }
}