﻿using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Collections.Generic;

namespace Net.Moloni.Model
{
    public class ProductInfo : BaseResource
    {
        public int Id { get; set; }

        public ProductType Type { get; set; }

        public string Name { get; set; }

        public string Reference { get; set; }

        public string EAN { get; set; }

        public double Price { get; set; }

        public double Stock { get; set; }

        public AtProductCategory AtProductCategory { get; set; }

        public string Image { get; set; }

        public MeasurementUnitInfo MeasurementUnit { get; set; }

        public IEnumerable<ProductTaxInfo> ProductTaxes { get; private set; }

        internal ProductInfo(JToken jToken) : base(jToken)
        {
            this.Id = jToken.Value<int>("product_id");
            this.Type = (ProductType)jToken.Value<int>("type");
            this.Name = jToken.Value<string>("name");
            this.Reference = jToken.Value<string>("reference");
            this.EAN = jToken.Value<string>("ean");
            this.Price = jToken.Value<double>("price");
            this.Stock = jToken.Value<double>("stock");
            this.MeasurementUnit = new MeasurementUnitInfo(jToken.Value<JToken>("measurement_unit"));
            this.ProductTaxes = jToken.Value<JArray>("taxes").Select(t => new ProductTaxInfo(t));
            this.Image = jToken.Value<string>("image");

            var atProductCategoryVal = jToken.Value<string>("at_product_category");
            this.AtProductCategory = ((!string.IsNullOrEmpty(atProductCategoryVal)))
                ? (AtProductCategory)Enum.Parse(typeof(AtProductCategory), atProductCategoryVal)
                : AtProductCategory.NotApplicable;
        }
    }

    public enum ProductType
    {
        Product = 1,
        Service = 2,
        Other = 3
    }

    public enum AtProductCategory
    {
        NotApplicable = 0,
        /// <summary>
        /// Goods
        /// </summary>
        M,
        /// <summary>
        /// Raw Materials, Subsidiaries and Consumer Goods
        /// </summary>
        P,
        /// <summary>
        /// Finished and Intermediate Products
        /// </summary>
        A,
        /// <summary>
        /// By-products, Waste and Scrap
        /// </summary>
        S,
        /// <summary>
        /// Products and Work in Progress
        /// </summary>
        T
    }
}
