// See http://d.hatena.ne.jp/fits/20090815/1250352312

package perm

import perm._

import scala.actors.Actor._
import scala.actors.remote.RemoteActor.alive
import scala.actors.remote.RemoteActor.register


object solverNode {

    def main(args : Array[String]) : Unit = {
        val name = Symbol("Magicsquare") // シンボルの設定
        val defaultPort = 9000
        val port = if (args.length > 0) Integer.parseInt(args(0)) else defaultPort //ポート番号の設定

        actor {
            alive(port)
            register(name, self)
            println("start loop")
            loop {
                receive {
                    case msg => {
                            Console.println("received=" + msg)
                            try {
                                // reply(msg)
                                reply(doTask(msg))
                            } catch {
                                case e => reply("Error=" + e.toString)
                            }
                        }
                }
            }
        }
    }

    def doTask(msg:Any) = {
        var ans = List[List[Int]]()
        println(msg)
        msg match {
            case sizeX:: startX :: endX :: _ =>
                {
                    println("" + sizeX + "," + startX + "," + endX)
                    val size = (sizeX.asInstanceOf[BigInt]).intValue
                    val start = (startX.asInstanceOf[BigInt])
                    val end = (endX.asInstanceOf[BigInt])
                    val ls0 = List.range(1, size * size + 1)
                    val ms = MagicsquareCheck(size)
                    var i = start
                    while (i < end) {
                        val ls = Perms.perm_nth(ls0, i)
                        ms.scan(ls) match {
                            case (skip, res) => {
                                    if (res != null) {
                                        println("-- " + res)
                                        ans = ans + res
                                    }
                                    i += skip
                                }
                        }
                    }
                    (ans, ans.size)
                }
            case _ => (msg, null)
        }
    }
}