using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using WebApplication1.Models;

namespace WebApplication1.Repositories.ArticleCommerceRepository {
  public class ArticleCommerceRepositoryTsv : ArticleCommerceRepositoryBase {
    private static string FichierCaddie => $"{HttpRuntime.AppDomainAppPath}Repositories/ArticleCommerceRepository/Caddie_{HttpContext.Current.Session.SessionID}.tsv";
    private static string FichierStock = $"{HttpRuntime.AppDomainAppPath}Repositories/ArticleCommerceRepository/Stock.tsv";
    public override void ViderCaddie() {
      if( File.Exists( FichierCaddie ) )
        File.Delete( FichierCaddie );
    }
    private static List<ArticleCommerce> ListerDesArticles( string fichier ) {
      if( !File.Exists( fichier ) )
        return new List<ArticleCommerce>();
      using( var r = new StreamReader( fichier ) ) {
        return r.ReadToEnd().Split( '\n' ).Where( s => !string.IsNullOrWhiteSpace( s ) ).Select( s => s.Split( '\t' ) ).Select( t => new ArticleCommerce( Guid.Parse( t[0] ), decimal.Parse( t[1] ), int.Parse( t[2] ), t[3] ) ).ToList();
      }
    }
    public override IList<ArticleCommerce> ListerStock() => ListerDesArticles( FichierStock );
    public override IList<ArticleCommerce> ListerCaddie() => ListerDesArticles( FichierCaddie );
    public override ArticleCommerce AjouterAuCaddie( Guid articleCommerceId ) {
      var caddie = ListerCaddie();
      ArticleCommerce ac = caddie.FirstOrDefault( a => a.Id == articleCommerceId );
      if( ac != null ) {
        ac.Quantite++;
      }
      else {
        var articleEnStock = ListerStock().First( a => a.Id == articleCommerceId );
        ac = new ArticleCommerce( articleEnStock.Id, articleEnStock.PrixVente, 1, articleEnStock.Nom );
        caddie.Add( ac );
      }
      using( var writer = new StreamWriter( FichierCaddie ) ) {
        foreach( var a in caddie )
          writer.Write( $"{a.Id}\t{a.PrixVente}\t{a.Quantite}\t{a.Nom}\n" );
      }
      return ac;
    }
  }
}
