Vue.component('info-category', {
    props: ['group_id', 'category', 'category_index'],
    template: `
    <div class="">
    <table>
        <tr is="info-item"
            v-for="(item, index) in category.list"
            v-bind:group_id="group_id"
            v-bind:attr="item"
            v-bind:category_index="category_index"
            v-bind:category_id="category.id"
        ></tr>
    </table>
    </div>`
  });
Vue.component('info-item', {
    props: ['group_id', 'attr', 'category_index', 'category_id'],
    data: function() {
           return  {
	      for_id: 'field[' + this.category_id + '][' + this.attr.id + ']',
	   }},
    template: `
    <tr
>
        <td><label for="{{for_id}}">{{ attr.id }}</label></td>
        <td><input type="text" id="{{for_id}}" name="{{for_id}}"
		v-bind:value="attr.value"
                v-on:change=""
        ></td>
    </tr>`
  });

Vue.component('attribute-category', {
    props: ['group_id', 'category', 'category_index'],
    template: `
    <div class="AttributeClass">
    <h3>{{ category.id }} - {{category.priority}} - {{ category.sum }}</h3>
    <table>
        <tr is="attribute-item"
            v-for="(item, index) in category.list"
            v-bind:group_id="group_id"
            v-bind:attr="item"
            v-bind:category_index="category_index"
        ></tr>
    </table>
    </div>`
  });

Vue.component('attribute-item', {
    props: ['group_id', 'attr', 'category_index'],
    data: {
	hover_index: -1,
	hover_class: ''
    },
    methods: {
  //      mouseOver: function(event){
//		computeAttrHoverClass(this.attr.value, this.hover_index, circle_index);}	},

        mouseOver: function(event){
		this.hover_index = event.target.attributes.circle_index.value;
//		console.log(this.hover_index)
console.log(event.target.attributes.circle_index.value)
//hover_index = this.circle_index;
//            this.hover_index = hover_index;
//		this.hover_class = 
//	this.$emit('change');
        },
        mouseOut: function(hover_index){
            this.hover_index = -1;
        },
        computeAttrHoverClass: function(attr_value, hover_index, circle_index) {
		console.log(attr_value, hover_index, circle_index)
		return circle_index>attr_value ? (hover_index<=circle_index ? 'circleGreen' : '') : hover_index>=circle_index ? 'circleRed' : '';
	}
    },
    template: `
    <tr>
        <td>{{ attr.id }}</td>
        <td>{{ attr.value }}</td>
        <td>
            <span class="circle" 
                v-for="n in 5" 
                v-bind:circle_index="n"
                v-bind:class="[{circleBlack: n <= attr.value}, this.hover_class]"
                v-on:click="{attr.value = n; this.app_form.computeAttrSum(group_id, category_index); this.app_form.computeAttrPriorities(group_id, category_index);}"
                v-on:mouseover="{mouseOver($event)}"
                v-on:mouseout="{mouseOut($event)}"
            ></span>
        </td>
    </tr>`
  });
//this.app_form.computeAttrHoverClass(attr.value, hover_index, n);

Vue.component('priority-item', {
    props: ['priority'],
    template: `
    <tr>
        <td>{{ priority.id }}</td>
        <td>{{ priority.value }}</td>
        <td>{{ priority.assignedTo }}</td>
    </tr>`
  });

Vue.component('skill-spell-category', {
    props: ['group_id', 'category', 'category_index'],
    template: `
    <div class="AttributeClass">
    <h3>{{ category.id }}</h3>
    <table>
        <tr is="skill-spell-item"
            v-for="(item, index) in category.list"
            v-bind:group_id="group_id"
            v-bind:attr="item"
            v-bind:category_index="category_index"
        ></tr>
    </table>
    </div>`
  });

Vue.component('skill-spell-item', {
    props: ['group_id', 'attr','category_index'],
    template: `
    <tr>
        <td>{{ attr.id }}</td>
        <td>{{ attr.value }}</td>
        <td>
            <div class="circle" 
                v-for="n in 5" 
                v-bind:class="{circleBlack: n <= attr.value}"
                v-on:click="{attr.value = attr.value==n ? n-1 : n; this.app_form.computeAttrSum(group_id, category_index);}"
            ></div>
        </td>
    </tr>`
  });



const isExist = (ref)       => typeof ref != 'undefined' && ref!=null;
const isArray = (ref)       => typeof ref=='object' && ref!=null;
const isFunction = (ref)    => typeof ref=='function' && ref!=null;
const isObject = (ref)      => typeof ref=='object' && ref!=null;
const getValue = (ref, def) => isExist(ref) ? ref : def;

function cloneObject(obj)
	{
	return JSON.parse(JSON.stringify(obj));	//	return Object.assign({}, obj); - assign nefunguje spravne u parseru
	}

function cloneArray(arr)
	{
	return JSON.parse(JSON.stringify(arr));	//	return Object.assign({}, arr); - assign nefunguje spravne u parseru
	}

var app_form = new Vue({ 
    name: 'App form',
    el: '#app_form',
    data: function() {
        var data = {
            props: {},
       
            form_data: {},
//            form_data: {"info":[{"id":"info","list":[{"id":"Name","value":" --- BLANK --- "},{"id":"Age","value":""},{"id":"Description","value":""}]}],"attributes":[{"id":"Physical","list":[{"id":"Strength","value":1},{"id":"Dexterity","value":1},{"id":"Stamina","value":1}],"priority":"C","sum":3},{"id":"Social","list":[{"id":"Charisma","value":1},{"id":"Manipulation","value":1},{"id":"Composure","value":1}],"priority":"C","sum":3},{"id":"Mental","list":[{"id":"Intelligence","value":1},{"id":"Wits","value":1},{"id":"Resolve","value":1}],"priority":"C","sum":3}],"skills":[{"id":"Physical","list":[{"id":"Athletics","value":0},{"id":"Melee","value":0},{"id":"Larceny","value":0},{"id":"Shooting","value":0},{"id":"Casting","value":0},{"id":"Riding","value":0},{"id":"Flying","value":0},{"id":"Brewing","value":0},{"id":"Stealth","value":0},{"id":"Survival1","value":0},{"id":"Brawl","value":0},{"id":"Survival2","value":0}],"sum":0},{"id":"Social","list":[{"id":"Empathy","value":0},{"id":"Intimidation","value":0},{"id":"Persuasion","value":0},{"id":"Subterfuge","value":0},{"id":"Animal Ken","value":0},{"id":"Expression","value":0},{"id":"Etiquette","value":0}],"sum":0},{"id":"Mental","list":[{"id":"Awareness","value":0},{"id":"Investigation","value":0},{"id":"Ancient Runes","value":0},{"id":"Herbology","value":0},{"id":"Magic Theory","value":0},{"id":"Potions","value":0},{"id":"Magical Creatures","value":0},{"id":"Crafts","value":0}],"sum":0}],"spells":[{"id":"Physical","list":[{"id":"push","value":0},{"id":"shield","value":0},{"id":"rope","value":0},{"id":"disarm","value":0},{"id":"magic arm","value":0}],"sum":0},{"id":"Social","list":[{"id":"charm","value":0},{"id":"intimidate","value":0},{"id":"social defense charm","value":0}],"sum":0},{"id":"Mental","list":[{"id":"examine magic","value":0},{"id":"mind defense","value":0},{"id":"mind attack","value":0}],"sum":0},{"id":"Elemental","list":[{"id":"fire bolt","value":0},{"id":"lightning","value":0},{"id":"freeze","value":0}],"sum":0}]},

            form_data_structure: {
                info: {
                    id: "header-id",
                    list: [
                        { id: "item-id", value: "" }
                    ]
                },
                attributes: {
                    id: "header-id",
                    list: [
                        { id: "item-id", value: 1 }
                    ],
                    priority: "C",
                    sum: 3
                },
                skills: {
                    id: "header-id",
                    list: [
                        { id: "item-id", value: 0 }
                    ],
                    sum: 0
                },
                spells: {
                    id: "header-id",
                    list: [
                        { id: "item-id", value: 0 }
                    ],
                    sum: 0
                }
	    }
	}
//            }	// data-as-object
	var blank, structrure;
	data.props = config;
	blank     = cloneObject(data.props.CharacterSheetBlank);
	structure = cloneObject(data.form_data_structure);
	this.formDataUpdateBySheet(data.form_data, structure, blank);

    return data; // data-as-function       
    },

//    created: function() {
//console.log('app-form created...');
//    },

//  mounted: function() {
//console.log('app-form mounted...');
//  },

    methods: {

        computeAttrHoverClass: function(attr_value, hover_index, circle_index) {
		return circle_index>attr_value ? (hover_index<=circle_index ? 'circleGreen' : '') : hover_index>=circle_index ? 'circleRed' : '';
	},

        computeAttrSum: function(group_id, category_index) { 
//console.log(group_id, category_index, JSON.stringify(this.form_data[group_id][category_index]));
            var sum = 0, category = this.form_data[group_id][category_index], list = category.list, len = list.length;
            for(var i = 0; i < len; i++) {
                sum += parseInt(list[i].value);
            }
            category.sum = sum;
//console.log(this.form_data[group_id][category_index].sum);
            return true;
        },

        computeAttrPriorities: function(group_id, category_index)	//event, index
            {  
//console.log('computePriorities');
                var group = this.form_data[group_id], i, j, tmp, i_end;
		tmp = [];
		for (i in group)
			{
//console.log(group[i].id)
			tmp[i] = {sum: group[i].sum, order: i};
			i++;
			}
		tmp.sort( function(a, b) {return b.sum - a.sum;} );
//console.log(JSON.stringify(tmp))
		i_end = i;
		for (i=0; i<i_end; i++)
			{
			group[tmp[i].order].priority = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.charAt(i);
			}
            },

sheetBlankParser: function (blank, sheet)	// parse charactesr_sheet to list of [field_id, value]
	{
	var i, fn;
	fn = 'sheetBlankParser';
	if (!isObject(blank) || !isObject(sheet))
		{
		return;
		}
	for(i in blank)
		{
		if (!isObject(sheet) || !(i in sheet))
			{
			continue;
			}
		if (isObject(blank[i]))	// object, repeat
			{
			if (!isObject(sheet[i]))
				{
				this.error(fn, 'Value in "parsed object" is not type Object.');
				}
			this.sheetBlankParser(blank[i], sheet[i]);
			}
		else	{
			blank[i] = sheet[i];	// value, save
			}
		}
	},

//dataCreateNewStructure: function()
//	{
//	blank  = cloneObject(this.props.CharacterSheetBlank);
//	}

//formDataNew: function()
//	{
//	this.form_data = cloneObject(this.form_data_structure);
//	},

formDataUpdateByBlankSheet: function()
	{
        this.sheetImport(this.props.CharacterSheetBlank);
	},

formDataUpdateBySheet: function(out, structure, sheet)
	{
console.log('formDataUpdateBySheet');
	var i, j, k, jj, kk;
	for (i in structure)			// i = group / atributtes
		{
		if (!isObject(structure[i]) || !isObject(sheet[i]))
			{
			return;
			}
		if (!isArray(out[i]))
			{
			out[i] = [];
			}
//console.log('-- '+i+' --')
		jj = 0;
		for (j in sheet[i])			// j = category / physical
			{
			if (!isObject(sheet[i][j]))
				{
				return;
				}
//console.log('-- '+j+' --')
			if (!isObject(out[i][jj]))
				{
				out[i][jj] = cloneObject(structure[i]);
				}
			out[i][jj].id = j;							// copy group-id
			if (isExist(structure[i].list) && (!isExist(out[i][jj].list) || !isArray(out[i][jj].list)))	// create plistriority, if not exist
				{
				out[i][jj].list = cloneObject(structure[i].list);
				}
			if (isExist(structure[i].sum) && !isExist(out[i][jj].sum))			// create sum, if not exist
				{
				out[i][jj].sum = structure[i].sum;
				}
			if (isExist(structure[i].priority) && !isExist(out[i][jj].priority))		// create priority, if not exist
				{
				out[i][jj].priority = structure[i].priority;
				}
//console.log(JSON.stringify(structure[i].list[0]))
			temp = cloneObject(structure[i].list[0]);
			kk = 0;
			for (k in sheet[i][j])
				{
//console.log(i, j, k)
				if (!isExist(out[i][jj].list[kk]))
					{
					out[i][jj].list[kk] = cloneObject(temp);
					}
				out[i][jj].list[kk].id    = k;
//console.log(i, j, JSON.stringify(sheet[i][j]))
				out[i][jj].list[kk].value = sheet[i][j][k];
				kk++;
//console.log('-')
				}
			jj++;
			}
		}
	},

sheetImport: function(sheet)
	{
	var fn = 'sheetImport';
console.log('start '+fn);
//console.log(fn + JSON.stringify(character_sheet));
	var i, i_end, list, fields, blank, structrure;
	sheet = isObject(sheet) ? sheet : {};
	blank = cloneObject(this.props.CharacterSheetBlank);
	this.sheetBlankParser(blank, sheet);	// save to blank
//	structure = cloneObject(this.form_data_structure);
	structure = this.form_data_structure;
	this.formDataUpdateBySheet(this.form_data, structure, blank);
//console.log('form-data')
//console.log('form-data', JSON.stringify(this.form_data))
	}

	}
/*
exportParser(template, obj, out)	// parse charactesr_sheet to list of [field_id, value]
	{
	var i, fn, id;
	fn = 'exportParser';
	if (!isObject(obj))
		{
		return false;
		}
	for(i in template)
		{
//console.log('exportParser '+JSON.stringify(obj))
		if (isObject(template[i]))
			{
			this.exportParser(template[i], obj, out[i]);
			}
		else	{
			id = template[i];
			if (!(id in obj) || !isExist(obj[id].value))
				{
				this.error(fn, 'Field or Field.value not exist in character_fields. ' + String(id));
				return;
				}
			out[i] = obj[id].value;
			}
		}
	}

exportCharacterSheet(value)
	{
	var fn = 'exportCharacterSheet';
console.log(fn);
	var character_sheet  = cloneObject(this.props.config.CharacterSheetBlank);
	var character_fields = cloneObject(this.state.character_fields);
//console.log('exportCharacterSheet '+JSON.stringify(character_sheet))
	this.exportParser(this.props.config.parser_template, character_fields, character_sheet);
console.log('exportCharacterSheet ' + JSON.stringify(character_sheet));
	return;
	}
	},

//console.log(JSON.stringify(this.form_data['info']))
//console.log(JSON.stringify(this.form_data['attributes']))
//console.log(JSON.stringify(this.form_data['skills']))
//console.log(JSON.stringify(this.form_data['spells']))
//	this.formDataUpdateByBlankSheet();
//	this.props = config;
//        this.sheetImport(this.props.CharacterSheetBlank);
//console.log(JSON.stringify(this.form_data))

//	this.formDataUpdateByBlankSheet()
//  	this.formDataUpdateByBlankSheet().then();	//data => {    	this.form_data = data;}

//	var i, i_end, list, fields, blank, structrure;
//	blank     = cloneObject(this.props.CharacterSheetBlank);
//	structure = cloneObject(this.form_data_structure);
//	this.formDataUpdateBySheet(this.form_data, structure, blank);
//console.log(JSON.stringify(this.form_data))

*/
});
		

//----------------------------
/*
	main: {
                list: [
                    { id: "Name", value: "" },
                    { id: "Age", value: "" },
                    { id: "Description", value: "" }
                ],
	attributes:
		{
                id: "Physical",                 
                list: [
                    { id: "Strength", value: 1 },
                    { id: "Dexterity", value: 1 },
                    { id: "Stamina", value: 1 },
                ],
                priority: "A",
		sum: 3
            },
            {
                id: "Social",                 
                list: [
                    { id: "Charisma", value: 1 },
                    { id: "Manipulation", value: 1 },
                    { id: "Composure", value: 1 }     
                ],
                priority: "B",
		sum: 3
            },
            {
                id: "Mental",                 
                list: [
                    { id: "Intelligence", value: 1 },
                    { id: "Wits", value: 1 },
                    { id: "Resolve", value: 1 } 
                ],
                priority: "C",
		sum: 3
            },
	skills:
		{
		"Physical":
			{
			"Athletics": 32,
			"Melee": 33,
			"Larceny": 34,
			"Shooting": 35,
			"Casting": 36,
			"Riding": 37,
			"Flying": 38,
			"Brewing": 39,
			"Stealth": 40,
			"Survival1": 41,
			"Brawl": 42,
			"Survival2": 43
			},
		"Social":
			{
			"Empathy": 45,
			"Intimidation": 46,
			"Persuasion": 47,
			"Subterfuge": 48,
			"Animal Ken": 49,
			"Expression": 50,
			"Etiquette": 51
			},
		"Mental":
			{
			"Awareness": 53,
			"Investigation": 54,
			"Ancient Runes": 55,
			"Herbology": 56,
			"Magic Theory": 57,
			"Potions": 58,
			"Magical Creatures": 59,
			"Crafts": 60,
		        }
		},
	"Spells":
		{
		"Physical":
			{
			"push": 72,
			"shield": 73,
			"rope": 74,
			"disarm": 75,
			"magic arm": 76
			},
		"Social":
			{
			"charm": 78,
			"intimidate": 79,
			"social defense charm": 80
			},
		"Mental":
			{
			"examine magic": 82,
			"mind defense": 83,
			"mind attack": 84
		        },
		"Elemental":
			{
			"fire bolt": 86,
			"lightning": 87,
			"freeze": 88
		        }
		}
*/
/*
        Attributes: [
            {
                id: "Physical",                 
                list: [
                    { id: "Strength", value: 1 },
                    { id: "Dexterity", value: 1 },
                    { id: "Stamina", value: 1 },
                ],
                priority: "A",
		sum: 3
            },
            {
                id: "Social",                 
                list: [
                    { id: "Charisma", value: 1 },
                    { id: "Manipulation", value: 1 },
                    { id: "Composure", value: 1 }     
                ],
                priority: "B",
		sum: 3
            },
            {
                id: "Mental",                 
                list: [
                    { id: "Intelligence", value: 1 },
                    { id: "Wits", value: 1 },
                    { id: "Resolve", value: 1 } 
                ],
                priority: "C",
		sum: 3
            }
        ],
        AttributePrioritiesRestricitons: [
            {id: "A", sum: 5},
            {id: "B", sum: 4},
            {id: "C", sum: 3}
        ]
*/



//var app = {
//  //  data: {
//    methods: {








// https://beautifier.io/
