//  MeCab -- Yet Another Part-of-Speech and Morphological Analyzer
//
//  Copyright(C) 2001-2006 Taku Kudo <taku@chasen.org>
//  Copyright(C) 2004-2006 Nippon Telegraph and Telephone Corporation
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace NMeCab.Core
{
    public class Connector
    {
        #region Const / Field

        private const string MatrixFile = "matrix.bin";

        private short[] matrix;

        public ushort LSize { get; private set; }

        public ushort RSize { get; private set; }

        #endregion

        #region Open

        public void Open(MeCabParam param)
        {
            string fileName = Path.Combine(param.DicDir, Connector.MatrixFile);
            this.Open(fileName);
        }

        public void Open(string fileName)
        {
            using (FileStream stream = new FileStream(fileName, FileMode.Open))
            using (BinaryReader reader = new BinaryReader(stream))
            {
                this.Open(reader, fileName);
            }
        }

        public void Open(BinaryReader reader, string fileName = "")
        {
            this.LSize = reader.ReadUInt16();
            this.RSize = reader.ReadUInt16();

            this.matrix = new short[this.LSize * this.RSize];
            for (int i = 0; i < this.matrix.Length; i++)
            {
                this.matrix[i] = reader.ReadInt16();
            }

            if (reader.BaseStream.ReadByte() != -1)
                throw new MeCabInvalidFileException("file size is invalid", fileName);
        }

        #endregion

        #region Cost

        public int Cost(MeCabNode lNode, MeCabNode rNode)
        {
            return this.matrix[lNode.RCAttr + this.LSize * rNode.LCAttr] + rNode.WCost;
        }

        #endregion
    }
}
