/*
 * Copyright 2007 nori090
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package jimmy.command;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import jimmy.ConvertUtil;
import jimmy.RC4;
import jimmy.WinnyProtocolException;
import jimmy.util._ByteArrayInputStream;

/**
 * winny protocol header command
 * 
 * @author nori090
 * @version $Rev: 17 $ $Date: 2008-03-25 22:45:24 +0900 (Tue, 25 Mar 2008) $
 */
public class Command00
    extends Command {

    static final byte[] CERT_KEY = new byte[] { 0x39, 0x38, 0x37, 0x38, 0x39, 0x61, 0x73, 0x6a };

    static final String KEY = "98789asj";

    public static final String MAJOR = "Winny Ver2.0b1  ";

    public static final int MINOR = 12710;

    int minor = MINOR;

    String major = MAJOR;

    @Override
    void rawDataPack()
        throws WinnyProtocolException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            out.write( ConvertUtil.toLittleEndianBytes( minor ) );
            out.write( major.getBytes( "UTF-8" ) );
            data = encrypt( out.toByteArray() );
        }
        catch ( Exception e ) {
            throw new WinnyProtocolException( e );
        }
        finally {
            try {
                // ByteArrayOutputStreamは意味内けど
                out.close();
            }
            catch ( Exception e ) {
                e.printStackTrace();
            }
        }
    }

    @Override
    void rawDataUnpack()
        throws WinnyProtocolException {
        try {
            byte[] d_data = decrypt( data );
            _ByteArrayInputStream reader = new _ByteArrayInputStream( d_data );
            minor = ConvertUtil.littleEndianBytes2int( reader.read( 4 ) );
            major = new String( reader.read( d_data.length - 4 ), "UTF-8" );
        }
        catch ( IOException e ) {
            throw new WinnyProtocolException( e );
        }
    }

    byte[] encrypt( byte[] bs )
        throws WinnyProtocolException {
        return RC4.encrypt( CERT_KEY, bs );
    }

    byte[] decrypt( byte[] bs )
        throws WinnyProtocolException {
        return RC4.decrypt( CERT_KEY, bs );
    }

    public int getMinor() {
        return minor;
    }

    public void setMinor( int minor ) {
        this.minor = minor;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor( String major ) {
        this.major = major;
    }
}
